clear all;
clc;

tic
disp('Loading data...');
load 7nn30small;
l = 5000;

k = 7;
lam = 1;
[n,s] = size(V);

C = 10;

Y = yU(1:l)';
Y = [(Y==0) (Y==1) (Y==2) (Y==3) (Y==4) (Y==5) (Y==6) (Y==7) (Y==8) (Y==9)];
Y = Y - (Y==0);
Y = double(Y);
[l,c] = size(Y);
disp('Data loaded!');

Ivec = reshape(repmat((1:n)',1,k-1),[],1);
V = V(:,1:s);
n = size(V,1);
QC = V(Ivec,:) - V(IDXvec,:);
clear Ivec;
clear IDXvec;

P = zeros(l,s,c);
for i = 1:c
    P(:,:,i) = repmat(Y(:,i),1,s).*V(1:l,:);
end
Q = V(l+1:n,:);
clear V;

disp('Start optimization...');
tic

cvx_begin sdp
cvx_solver sedumi
    variable t
    variable gam(s,c)
    variable M(s,s) symmetric
    variable del(l,1) nonnegative
    variable bb(c,1)
    minimize (t-lam*trace(M)+2*C*ones(1,l)*del);
    for i=1:c
        [M gam(:,i);gam(:,i)' t] >= 0;
        P(:,:,i)*gam(:,i) + bb(i)*Y(:,i) - ones(l,1) + del >= 0;
    end
    sum(QC*M.*QC,2) <= Dvec
    M == semidefinite(s);
cvx_end

toc

[~,Ypred] = max(Q*gam+repmat(bb',n-l,1),[],2);
Ypred = int8(Ypred)-1;

label = int8(yU(l+1:n)');
calacc(Ypred,label);
save(['res/MMTL',int2str(l),'K',int2str(k),'S',int2str(s),'M',int2str(lam)]);